/*************************************************************************
	> File Name: udp_client.cc
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/01 17:20
 ************************************************************************/

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>

const int SIZE = 1024;

uint16_t serverport;
std::string serverip;

static void usage(const std::string &proc)
{
    std::cout << "Usage:" << proc << " ip port." << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3) {
        usage(argv[0]);
        exit(1);
    }
    int sock;
    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        std::cout << "socket error." << std::endl;
        exit(1);
    }
    serverport = atoi(argv[2]);
    serverip = argv[1];
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    std::string command;
    char buffer[SIZE];
    while (1) {
        std::cout << "Please input command:";
        std::getline(std::cin, command);
        if (command == "quit") {
            break;
        }
        sendto(sock, command.c_str(), command.size(), 0, (struct sockaddr*)&server, sizeof server);
        struct sockaddr_in temp;
        socklen_t len = sizeof temp;
        memset(buffer, 0, sizeof buffer);
        ssize_t s = recvfrom(sock, buffer, sizeof buffer, 0, (struct sockaddr*)&temp, &len);
        if (s > 0) {
            std::cout << buffer << std::endl;
        }
    }
    return 0;
}
